package com.qcby.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcby.common.exception.BusinessException;
import com.qcby.entity.TOrder;
import com.qcby.entity.TProduct;
import com.qcby.entity.TAddress;
import com.qcby.entity.TProductSpecification;
import com.qcby.form.TOrderCreateForm;
import com.qcby.form.TOrderListForm;
import com.qcby.mapper.TOrderMapper;
import com.qcby.mapper.TProductMapper;
import com.qcby.mapper.TAddressMapper;
import com.qcby.mapper.TUserMapper;
import com.qcby.mapper.TProductSpecificationMapper;
import com.qcby.service.TOrderService;
import com.qcby.vo.PageVO;
import com.qcby.vo.TOrderDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2025-02-04
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {
    @Autowired
    private TOrderMapper orderMapper;
    @Autowired
    private TProductMapper productMapper;
    @Autowired
    private TAddressMapper addressMapper;
    @Autowired
    private TUserMapper userMapper;
    @Autowired
    private TProductSpecificationMapper specificationMapper;

    /**
     * 订单查询
     * @param orderListForm
     * @return
     */
    @Override
    public PageVO orderList(TOrderListForm orderListForm) {
        Page<TOrder> page = new Page<>(orderListForm.getPage(), orderListForm.getLimit());
        Integer userId = userMapper.selectIdFromName(orderListForm.getUserName());
        
        QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(userId != null, "user_id", userId)
                .eq(orderListForm.getOrderStatus() != null, "order_status", orderListForm.getOrderStatus())
                .eq(orderListForm.getOrderId() != null, "order_id", orderListForm.getOrderId())
                .orderByDesc("version");
                
        Page<TOrder> resultPage = orderMapper.selectPage(page, queryWrapper);
        
        List<TOrderDetailVO> orderVOList = new ArrayList<>();
        for (TOrder order : resultPage.getRecords()) {
            TOrderDetailVO orderVO = convertToOrderDetailVO(order);
            orderVOList.add(orderVO);
        }
        
        PageVO pageVO = new PageVO();
        pageVO.setList(orderVOList);
        pageVO.setTotalCount(resultPage.getTotal());
        pageVO.setPageSize(resultPage.getSize());
        pageVO.setCurrPage(resultPage.getCurrent());
        pageVO.setTotalPage(resultPage.getPages());
        return pageVO;
    }

    @Override
    @Transactional
    public void createOrder(TOrderCreateForm form) {
        // 校验地址
        TAddress address = addressMapper.selectById(form.getAddressId());
        if (address == null) {
            throw new BusinessException("收货地址不存在");
        }
        
        // 创建订单
        TOrder order = new TOrder();
        order.setUserId(address.getUserId());
        order.setAddressId(form.getAddressId());
        order.setOrderTime(LocalDateTime.now());
        order.setOrderStatus("未支付");
        order.setDeliveryStatus("未发货");
        
        // 计算总价并检查库存
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (TOrderCreateForm.OrderItemForm item : form.getItems()) {
            // 查询商品
            TProduct product = productMapper.selectById(item.getProductId());
            if (product == null || product.getIsDeleted() == 1) {
                throw new BusinessException("商品不存在");
            }
            
            // 查询商品规格
            TProductSpecification spec = specificationMapper.selectById(item.getSpecificationId());
            if (spec == null || !spec.getProductId().equals(item.getProductId())) {
                throw new BusinessException("商品规格不存在或不匹配");
            }
            
            // 检查库存
            if (spec.getStock() < item.getQuantity()) {
                throw new BusinessException(String.format("商品[%s-%s]库存不足", product.getProductName(), spec.getSpecName()));
            }
            
            // 计算价格
            totalPrice = totalPrice.add(spec.getPrice().multiply(new BigDecimal(item.getQuantity())));
            
            // 扣减库存
            spec.setStock(spec.getStock() - item.getQuantity());
            specificationMapper.updateById(spec);
        }
        
        order.setTotalPrice(totalPrice);
        order.setVersion(LocalDateTime.now());
        orderMapper.insert(order);
        
        // 保存订单商品明细
        saveOrderItems(order.getOrderId(), form.getItems());
    }

    /**
     * 保存订单商品明细
     */
    private void saveOrderItems(Integer orderId, List<TOrderCreateForm.OrderItemForm> items) {
        for (TOrderCreateForm.OrderItemForm item : items) {
            TOrderItem orderItem = new TOrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setProductId(item.getProductId());
            orderItem.setSpecificationId(item.getSpecificationId());
            orderItem.setQuantity(item.getQuantity());
            
            // 获取规格信息
            TProductSpecification spec = specificationMapper.selectById(item.getSpecificationId());
            orderItem.setPrice(spec.getPrice());
            orderItem.setSubtotal(spec.getPrice().multiply(new BigDecimal(item.getQuantity())));
            
            orderItemMapper.insert(orderItem);
        }
    }

    @Override
    public TOrderDetailVO getOrderDetail(Integer orderId) {
        TOrder order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        return convertToOrderDetailVO(order);
    }

    @Override
    @Transactional
    public void payOrder(Integer orderId) {
        TOrder order = checkOrderExists(orderId);
        if (!"未支付".equals(order.getOrderStatus())) {
            throw new BusinessException("订单状态不正确");
        }
        
        order.setOrderStatus("已支付");
        order.setPayTime(LocalDateTime.now());
        order.setVersion(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public void deliverOrder(Integer orderId) {
        TOrder order = checkOrderExists(orderId);
        if (!"已支付".equals(order.getOrderStatus())) {
            throw new BusinessException("订单状态不正确");
        }
        
        order.setDeliveryStatus("已发货");
        order.setVersion(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public void applyRefund(Integer orderId) {
        TOrder order = checkOrderExists(orderId);
        if (!"已支付".equals(order.getOrderStatus()) && !"已发货".equals(order.getDeliveryStatus())) {
            throw new BusinessException("订单状态不正确");
        }
        
        order.setOrderStatus("退款中");
        order.setVersion(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public void confirmRefund(Integer orderId) {
        TOrder order = checkOrderExists(orderId);
        if (!"退款中".equals(order.getOrderStatus())) {
            throw new BusinessException("订单状态不正确");
        }
        
        order.setOrderStatus("已退款");
        order.setRefundTime(LocalDateTime.now());
        order.setVersion(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    @Override
    @Transactional
    public void markOrderException(Integer orderId, String reason) {
        TOrder order = checkOrderExists(orderId);
        
        order.setOrderStatus("异常");
        order.setVersion(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    private TOrder checkOrderExists(Integer orderId) {
        TOrder order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        return order;
    }

    private TOrderDetailVO convertToOrderDetailVO(TOrder order) {
        TOrderDetailVO orderVO = new TOrderDetailVO();
        BeanUtils.copyProperties(order, orderVO);
        
        // 设置用户信息
        String userName = userMapper.selectNameFromId(order.getUserId());
        orderVO.setUserName(userName);
        
        // 设置地址信息
        TAddress address = addressMapper.selectById(order.getAddressId());
        if (address != null) {
            orderVO.setReceiverName(address.getReceiverName());
            orderVO.setReceiverPhone(address.getReceiverPhone());
            orderVO.setAddress(String.format("%s%s%s%s", 
                address.getProvince(), 
                address.getCity(), 
                address.getDistrict(), 
                address.getDetailAddress()));
        }
        
        return orderVO;
    }
}
